package com.djhu.freepartner.core;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.logging.log4j.core.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class RestLog implements Serializable {
    private static final long serialVersionUID = -923171769156177216L;

    private static  ThreadLocal<DateFormat> format =new ThreadLocal<DateFormat>() ;

    private static final Logger logger = LoggerFactory.getLogger(RestLog.class);

    DateFormat getDateFormat(){
        if(format.get() == null){
            format.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
        }
        return format.get();
    }

    /**
     *对方IP
     */
    private String remoteAddr;

    /**
     * 本地端口
     */
    private int localPort;

    /**
     * 本地IP
     */
    private String localAddr;

    /**
     * 请求方法的uri
     */
    private String uri;

    /**
     * 请求参数
     */
//	private Map<String,String[]> requests;
    private Object[] parameters;

    /**
     * 请求参数，map结构
     */
    private Map<String,String[]> mapParameters;
    /**
     * 处理时间，毫秒
     */
    private long processTimeInMs;

    //	/**
//	 * 处理的方法
//	 */
    private String processMethod;

    //	/**
//	 * 处理的类
//	 */
    private String processClass;
    /**
     * 异常类
     */
    private String exceptionClassName;

    /**
     * 异常信息
     */
    private String exceptionMessage;


    /**
     * 开始时间
     */
    private long startTime=System.currentTimeMillis();

    /**
     * 调用时间
     */
    private String callTime =getDateFormat().format(new Date(startTime));

    /**
     * 返回结果
     */
    private RestRsp result ;

//    /**
//     * 返回message结果
//     */
//    private ResultMessage<?> resultMessage ;

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public static ThreadLocal<DateFormat> getFormat() {
        return format;
    }

    public static void setFormat(ThreadLocal<DateFormat> format) {
        RestLog.format = format;
    }

    public static Logger getLogger() {
        return logger;
    }

    public String getRemoteAddr() {
        return remoteAddr;
    }

    public void setRemoteAddr(String remoteAddr) {
        this.remoteAddr = remoteAddr;
    }

    public int getLocalPort() {
        return localPort;
    }

    public void setLocalPort(int localPort) {
        this.localPort = localPort;
    }

    public String getLocalAddr() {
        return localAddr;
    }

    public void setLocalAddr(String localAddr) {
        this.localAddr = localAddr;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public Object[] getParameters() {
        return parameters;
    }

    public void setParameters(Object[] parameters) {
        this.parameters = parameters;
    }

    public Map<String, String[]> getMapParameters() {
        return mapParameters;
    }

    public void setMapParameters(Map<String, String[]> mapParameters) {
        this.mapParameters = mapParameters;
    }

    public long getProcessTimeInMs() {
        return processTimeInMs;
    }

    public void setProcessTimeInMs(long processTimeInMs) {
        this.processTimeInMs = processTimeInMs;
    }

    public String getProcessMethod() {
        return processMethod;
    }

    public void setProcessMethod(String processMethod) {
        this.processMethod = processMethod;
    }

    public String getProcessClass() {
        return processClass;
    }

    public void setProcessClass(String processClass) {
        this.processClass = processClass;
    }

    public String getExceptionClassName() {
        return exceptionClassName;
    }

    public void setExceptionClassName(String exceptionClassName) {
        this.exceptionClassName = exceptionClassName;
    }

    public String getExceptionMessage() {
        return exceptionMessage;
    }

    public void setExceptionMessage(String exceptionMessage) {
        this.exceptionMessage = exceptionMessage;
    }

    public long getStartTime() {
        return startTime;
    }

    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }

    public String getCallTime() {
        return callTime;
    }

    public void setCallTime(String callTime) {
        this.callTime = callTime;
    }

    public RestRsp getResult() {
        return result;
    }

    public void setResult(RestRsp result) {
        this.result = result;
    }

    @Override
    public String toString() {
        JSONObject obj = new JSONObject();
        obj.put("callTime", callTime);
        obj.put("processTimeInMs", processTimeInMs+"");
        obj.put("remoteAddr", remoteAddr);
        obj.put("localAddr", localAddr);
        obj.put("localPort", localPort);
        obj.put("uri", uri);
        if(parameters ==null || parameters.length == 0 ){
            obj.put("parameters","");
        }else{
            try {
                String parametersStr =  JSONArray.fromObject(parameters).toString();
                if(parametersStr.length() > 1024){
                    //超过1024 个字节，返回前1024+...
                    parametersStr = parametersStr.substring(0, 1024)+"...";
                }
                obj.put("parameters",parametersStr);
            }catch (Exception e){
                obj.put("parameters",null);
            }
        }
        obj.put("processClass",processClass);
        obj.put("processMethod", processMethod);
        obj.put("exceptionClass", exceptionClassName);
        obj.put("exceptionMessage", exceptionMessage);

        //Assert.
        obj.put("returnCode", result.getCode());
        obj.put("returnMsg", result.getMsg());
        obj.put("uuid", result.getUuid());
        //根据返回值处理returnData转String
        if(result.getData() == null){
            //如果没有返回值，那么就是""
            obj.put("returnData", "");
        }else{
            Object returnData = result.getData();
            String dataStr = "";
//    		if(returnData instanceof List){
//    			//返回值是list，那么久显示 List of:对象名    size:数量
//    			List dataList = (List) returnData;
//    			if(dataList.size() > 0){
//    				dataStr ="List of:"+ dataList.get(0).getClass().getName()+" size:" + dataList.size();
//    			}
//    		}else if(returnData instanceof Object[]){
//    			//返回值是Array，那么久显示 Array of:对象名    length:数量
//    			Object[] dataArra = (Object[]) returnData;
//    			if(dataArra.length > 0){
//    				dataStr ="Array of:"+ dataArra[0].getClass().getName()+" length:" + dataArra.length;
//    			}
//    		}else{
            //如果
            if(returnData instanceof String){
                //String直接返回
                dataStr = (String) returnData;
            }else if(returnData instanceof Number){
                //如果是inter float double之类，返回toString
                dataStr = returnData.toString();
            }else if(returnData instanceof List || returnData.getClass().isArray()){
                //list 或者 array 转为jsonarray
//    			dataStr =  JSONArray.fromObject(returnData).toString();
                dataStr="\""+JSONArray.fromObject(returnData).toString()+"\"";
            }else{
                //其他对象转json
                dataStr =  "\"["+JSONObject.fromObject(returnData).toString()+"]\"";
            }
            if(dataStr.length() > 1024){
                //超过1024 个字节，返回前1024+...
                dataStr = dataStr.substring(0, 1024)+"...";
                if(dataStr.startsWith("\"[")&&!dataStr.endsWith("]\"")){
                    dataStr+="]\"";
                }
            }
//    		}
            obj.put("returnData",dataStr);
        }
        return obj.toString();
    }



//    public String toMessageString() {
//        JSONObject obj = new JSONObject();
//        obj.put("callTime", callTime);
//        obj.put("processTimeInMs", processTimeInMs+"");
//        obj.put("remoteAddr", remoteAddr);
//        obj.put("localAddr", localAddr);
//        obj.put("localPort", localPort);
//        obj.put("uri", uri);
//        if(parameters ==null || parameters.length == 0 ){
//            obj.put("parameters","");
//        }else{
//            String parametersStr =  JSONArray.fromObject(parameters).toString();
//            if(parametersStr.length() > 1024){
//                //超过1024 个字节，返回前1024+...
//                parametersStr = parametersStr.substring(0, 1024)+"...";
//            }
//            obj.put("parameters",parametersStr);
//        }
//        obj.put("processClass",processClass);
//        obj.put("processMethod", processMethod);
//        obj.put("exceptionClass", exceptionClassName);
//        obj.put("exceptionMessage", exceptionMessage);
////        Assert.notNull(resultMessage,"Return result can't be null!");
//        obj.put("returnCode", resultMessage.getStatus());
//        obj.put("returnMsg", resultMessage.getErrorInfo());
//        obj.put("suserid",resultMessage.getSuserid());
//        obj.put("uuid", resultMessage.getUuid());
//        //根据返回值处理returnData转String
//        if(resultMessage.getMessage() == null){
//            //如果没有返回值，那么就是""
//            obj.put("returnData", "");
//        }else{
//            Object returnData = resultMessage.getMessage();
//            String dataStr = "";
////    		if(returnData instanceof List){
////    			//返回值是list，那么久显示 List of:对象名    size:数量
////    			List dataList = (List) returnData;
////    			if(dataList.size() > 0){
////    				dataStr ="List of:"+ dataList.get(0).getClass().getName()+" size:" + dataList.size();
////    			}
////    		}else if(returnData instanceof Object[]){
////    			//返回值是Array，那么久显示 Array of:对象名    length:数量
////    			Object[] dataArra = (Object[]) returnData;
////    			if(dataArra.length > 0){
////    				dataStr ="Array of:"+ dataArra[0].getClass().getName()+" length:" + dataArra.length;
////    			}
////    		}else{
//            //如果
//            if(returnData instanceof String){
//                //String直接返回
//                dataStr = (String) returnData;
//            }else if(returnData instanceof Number){
//                //如果是inter float double之类，返回toString
//                dataStr = returnData.toString();
//            }else if(returnData instanceof List || returnData.getClass().isArray()){
//                //list 或者 array 转为jsonarray
//                dataStr =  JSONArray.fromObject(returnData).toString();
//            }else{
//                //其他对象转json
//                dataStr =  JSONObject.fromObject(returnData).toString();
//            }
//            if(dataStr.length() > 1024){
//                //超过1024 个字节，返回前1024+...
//                dataStr = dataStr.substring(0, 1024)+"...";
//            }
////    		}
//            obj.put("returnData",dataStr);
//        }
//        return obj.toString();
//    }

    public void saveLog(){
        logger.info(this.toString());
    }
}
